<template>
  <div class="toolbar">
  <el-button size="small" @click="onImportText">导入文本</el-button>
    <el-button size="small" @click="onImportLabels">导入标签</el-button>
    <el-button size="small" @click="onExportLabelsJson">导出标签json</el-button>
    <el-button size="small" @click="onImportProject">导入项目</el-button>
  <el-button size="small" @click="onExportAnnotations">导出标注excel</el-button>
  <el-button size="small" @click="onExportJsonAnnotations">导出标注json</el-button>
  <el-button size="small" @click="onExportMD">导出MarkDown</el-button>

    <el-button size="small" type="primary" @click="onExportProject">导出项目</el-button>
  </div>
</template>
<script setup lang="ts">
import { useApi } from '../api'
import { useDocStore } from '../store/doc'
import { useAnnoStore } from '../store/anno'
import { useLabelsStore } from '../store/labels'
const api = useApi()
const doc = useDocStore()
const anno = useAnnoStore()
const labels = useLabelsStore()

function onExportProject(){
  // 仅导出当前文本与右侧标注
  const payload = {
    doc: { id: undefined, title: undefined, content: doc.content, encoding: 'utf-8' },
    annotations: anno.list
  }
  // 兼容 Pinia ref，确保发送原始值
  // @ts-ignore
  if (payload.doc && payload.doc.content && payload.doc.content.value !== undefined) payload.doc.content = payload.doc.content.value
  // @ts-ignore
  if (payload.annotations && payload.annotations.value !== undefined) payload.annotations = payload.annotations.value
  api.exportProject(payload).then(res => {
    const data = JSON.stringify(res.data)
    const blob = new Blob([data], { type: 'application/json' })
    const a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = 'project.json'
    a.click()
    URL.revokeObjectURL(a.href)
  })
}
function onImportProject(){
  const inp = document.createElement('input')
  inp.type = 'file'
  inp.accept = '.json'
  inp.onchange = async () => {
    if(!inp.files || inp.files.length===0) return
    const f = inp.files[0]
    
    try {
      // 首先解析文件内容以获取导入的数据
      const fileContent = await f.text()
      const projectData = JSON.parse(fileContent)
      
      // 调用后端导入接口
      await api.importProject(f)
      
      // 清空当前标注
      anno.clearAll()
      
      // 重新加载导入的数据
      if (projectData.labels && Array.isArray(projectData.labels)) {
        labels.setItems(projectData.labels)
      }
      
      // 如果有文档数据，设置第一个文档的内容
      if (projectData.docs && Array.isArray(projectData.docs) && projectData.docs.length > 0) {
        const firstDoc = projectData.docs[0]
        if (firstDoc.content) {
          doc.setContent(firstDoc.content)
        }
      }
      
      // 如果有标注数据，设置标注
      if (projectData.annotations && Array.isArray(projectData.annotations)) {
        // 需要将标注数据格式化为前端期望的格式
        const formattedAnnotations = projectData.annotations.map((a: any) => ({
          id: a.id,
          label_id: a.label_id,
          start_offset: a.start_offset,
          end_offset: a.end_offset,
          text: a.text || ''
        }))
        anno.setList(formattedAnnotations)
      }
      
    } catch (error) {
      console.error('导入项目失败', error)
      // 如果解析失败，仍然尝试后端导入（可能是旧格式）
      try {
        await api.importProject(f)
        anno.clearAll()
      } catch (apiError) {
        console.error('API导入也失败', apiError)
      }
    }
  }
  inp.click()
}
function onImportText(){
  const inp = document.createElement('input')
  inp.type = 'file'
  inp.accept = '.txt,.docx'
  inp.onchange = async ()=>{
    if(!inp.files || inp.files.length===0) return
    const res = await api.uploadText(inp.files[0])
    if(res?.data?.content){
      doc.setContent(res.data.content)
      // 导入新文本后清空本地标注
      anno.clearAll()
    }
  }
  inp.click()
}
function onImportLabels(){
  // 仅导入标签（JSON），成功后清空标注
  const inp = document.createElement('input')
  inp.type = 'file'
  inp.accept = '.json'
  inp.onchange = async ()=>{
    if(!inp.files || inp.files.length===0) return
    const f = inp.files[0]
    const text = await f.text()
    try{
      const payload = JSON.parse(text)
      const arr = Array.isArray(payload) ? payload : (payload.labels || payload.data || [])
      if(Array.isArray(arr)){
        labels.setItems(arr)
        anno.clearAll()
      }else{
        console.warn('标签文件结构不符合预期')
      }
    }catch(e){
      console.error('标签导入失败', e)
    }
  }
  inp.click()
}
function onExportLabelsExcel(){
  api.exportLabelsExcel().then(res => {
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = 'labels.xlsx'
    a.click()
    URL.revokeObjectURL(a.href)
  })
}
function onExportAnnotations(){
  api.exportAnnotations().then(res => {
    const data = JSON.stringify(res.data)
    const blob = new Blob([data], { type: 'application/json' })
    const a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = 'annotations.json'
    a.click()
    URL.revokeObjectURL(a.href)
  })
}

function onExportJsonAnnotations(){
  // 导出标注为JSON格式
  const annotationsData = {
    annotations: anno.list.map(a => ({
      id: a.id,
      label_id: a.label_id,
      start_offset: a.start_offset,
      end_offset: a.end_offset,
      text: a.text
    }))
  }
  
  const data = JSON.stringify(annotationsData, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const a = document.createElement('a')
  a.href = URL.createObjectURL(blob)
  a.download = 'annotations.json'
  a.click()
  URL.revokeObjectURL(a.href)
}

function onExportMD(){
  // 导出标注为MarkDown格式
  let mdContent = doc.content || ''
  
  // 按照标注的起始位置排序
  const sortedAnnotations = [...anno.list].sort((a, b) => a.start_offset - b.start_offset)
  
  // 创建一个数组来存储每个字符位置的标注信息
  const positions: Array<{pos: number, type: 'open' | 'close', annotation: any}> = []
  
  // 为每个标注添加开始和结束位置
  sortedAnnotations.forEach(a => {
    positions.push({pos: a.start_offset, type: 'open', annotation: a})
    positions.push({pos: a.end_offset, type: 'close', annotation: a})
  })
  
  // 按位置排序，如果位置相同，先处理结束标签，再处理开始标签
  positions.sort((a, b) => {
    if (a.pos !== b.pos) return a.pos - b.pos
    if (a.type === 'close' && b.type === 'open') return -1
    if (a.type === 'open' && b.type === 'close') return 1
    return 0
  })
  
  // 构建新的内容
  let result = ''
  let lastPos = 0
  
  positions.forEach(({pos, type, annotation}) => {
    // 添加位置之间的原文
    result += mdContent.slice(lastPos, pos)
    
    if (type === 'open') {
      const label = labels.items.find(l => l.id === annotation.label_id)
      const labelName = label ? label.name : '未知标签'
      result += `<tag type="${labelName}">`
    } else {
      result += '</tag>'
    }
    
    lastPos = pos
  })
  
  // 添加剩余的内容
  result += mdContent.slice(lastPos)
  
  const blob = new Blob([result], { type: 'text/markdown' })
  const a = document.createElement('a')
  a.href = URL.createObjectURL(blob)
  a.download = 'annotations.md'
  a.click()
  URL.revokeObjectURL(a.href)
}

function onExportLabelsJson(){
  // 导出标签为JSON格式
  const labelsData = {
    labels: labels.items.map(label => ({
      id: label.id,
      parent_id: label.parent_id,
      name: label.name,
      color: label.color,
      description: label.description,
      sort: label.sort
    }))
  }
  
  const data = JSON.stringify(labelsData, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const a = document.createElement('a')
  a.href = URL.createObjectURL(blob)
  a.download = 'labels.json'
  a.click()
  URL.revokeObjectURL(a.href)
}
</script>
<style scoped>
.toolbar { padding:8px; display:flex; gap:8px; }
</style>
